package com.msb.user.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.msb.user.exception.CommonException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: microservices
 * @ClassName SentinelApi
 * @description:SentinelApi
 * @author: slfang
 * @create: 2024-01-04 09:14
 * @Version 1.0
 **/
@RestController
@Slf4j
public class SentinelApi {


    private static final String RESOURCE_NAME="API-RESOURCE";

    //http://localhost:8001/testAspect/12
    @GetMapping("/testAspect/{id}")
    @SentinelResource(value = "testAspect",
            fallback = "fallback",fallbackClass = CommonException.class,
            blockHandler = "handleException",blockHandlerClass = CommonException.class
    )
    public String testAspect(@PathVariable("id") Integer id){
        if(Integer.compare(id,Integer.parseInt("0")) == -1){
            throw new IllegalArgumentException("参数异常");
        }
        log.info("处理业务信息");
        return "处理业务信息";
    }



    @GetMapping("/getInfo")
    public String getInfo(){
        Entry entry = null;
        try{
            // 限流
            entry = SphU.entry(RESOURCE_NAME);
            // 被保护的业务逻辑
            String  str = "业务逻辑正常处理";
            log.info("============" + str + "==============");
            return str;
        } catch (BlockException e) {
            // 资源访问受阻，被限流或降级
            log.info("Block.......");
            return "业务被限流！";
        }catch (Exception e){
            Tracer.traceEntry(e,entry);
        }finally {
            if(entry != null){
                entry.exit();
            }
        }
        return null;
    }

    @PostConstruct
    private static void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        //设置受保护的资源
        rule.setResource("testAspect");
        // 设置流控规则 QPS
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 设置受保护的资源阈值
        rule.setCount(1);
        rules.add(rule);
        // 加载配置好的规则
        FlowRuleManager.loadRules(rules);
    }


}
